<?php
/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2021/12/1
 * Time: 10:07
 */
namespace app\admin\business;
use app\common\model\mysql\AdminUser;
use think\Exception;

class AdminUserLogin{
    public static function Login($data)
    {
        try{
            $adminUserObj = new AdminUser();
            $adminUser = self::getAdminUserByUsername($data['username']);
            if(empty($adminUser)){
                throw new Exception('不存在用户');
            }
            //4.判断密码
            if($adminUser['password'] != md5($data['password'].'_cun_abc')){
                throw new Exception('密码错误');
                //return show(config('status.error'),'密码错误');
            }
            //5.更改数据表
            $updateData = [
                'last_login_time' => time(),
                'last_login_ip' =>request()->ip(),
                'update_time' => time(),
            ];
            $res = $adminUserObj->updateById($adminUser['id'],$updateData);
            if(empty($res)){
                throw new Exception('登录失败');
                //return show(config('status.error'),'登录失败');
            }
        }catch (\Exception $e){
            //todo此处需要记录日志 $e->getMessage()
            throw new Exception('账号或者密码错误');
            //return show(config('status.error'),'内部错误 登录异常');
        }
        //6.存储session
        session(config('admin.session_admin'),$adminUser);
        return true;
    }

    /**
     * 根据用户名获取数据
     * @param $username
     * @return AdminUser|array|bool|null|\think\Model
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public static function getAdminUserByUsername($username)
    {
        $adminUserObj = new AdminUser();
        $adminUser = $adminUserObj->getAdminUserByUsername($username);
        if(empty($adminUser) || $adminUser->status !=config('status.mysql.table_normal')){
            return false;
        }
        $adminUser = $adminUser->toArray();
        return $adminUser;
    }
}